package com.hzhr.iot.web.controller;

import com.hzhr.iot.core.util.HzhrStringUtils;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.login.sdk.model.token.TokenModel;
import com.hzhr.iot.login.sdk.model.userCard.UserCardModel;
import com.hzhr.iot.login.sdk.service.Login_TokenService;
import com.hzhr.iot.user.sdk.model.action.ActionModel;
import com.hzhr.iot.user.sdk.model.user.UserModel;
import com.hzhr.iot.user.sdk.model.user_moreCompleteRegistInfo.User_MoreCompleteRegistInfoGetModel;
import com.hzhr.iot.user.sdk.model.user_moreCompleteRegistInfo.User_MoreCompleteRegistInfoModel;
import com.hzhr.iot.user.sdk.model.user_moreCompleteRegistInfo.User_MoreCompleteRegistInfoPutModel;
import com.hzhr.iot.user.sdk.model.user_registInfo.User_RegistInfoGetModel;
import com.hzhr.iot.user.sdk.model.user_registInfo.User_RegistInfoModel;
import com.hzhr.iot.user.sdk.model.user_registInfo.User_RegistInfoPostModel;
import com.hzhr.iot.user.sdk.service.User_ActionService;
import com.hzhr.iot.user.sdk.service.User_UserService;
import com.hzhr.iot.user.sdk.service.User_User_MoreCompleteRegistInfoService;
import com.hzhr.iot.user.sdk.service.User_User_RegistInfoService;
import com.hzhr.iot.web.Global;
import com.hzhr.iot.web.constant.ReturnCodeConst;
import com.hzhr.iot.web.constant.UserOptions;
import com.hzhr.iot.web.constant.UserType;
import com.hzhr.iot.web.controller.base.BaseController;
import com.hzhr.iot.web.model.Action;
import com.hzhr.iot.web.model.RoleExtent;
import com.hzhr.iot.web.model.User;
import com.hzhr.iot.web.model.response.BaseResponse;
import com.hzhr.iot.web.service.PicVericodeService;
import com.hzhr.iot.web.service.SMSService;
import com.hzhr.iot.web.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
@Api(description = "用户")
@RestController
public class UserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    Login_TokenService login_tokenService;
    @Autowired
    User_UserService user_userService;
    @Autowired
    PicVericodeService picVericodeService;
    @Autowired
    User_User_RegistInfoService user_user_registInfoService;
    @Autowired
    User_User_MoreCompleteRegistInfoService user_user_moreCompleteRegistInfoService;
    @Autowired
    User_ActionService user_actionService;
    @Autowired
    UserOptions userOptions;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    Global global;

    @Value("${aliyun.sms.isenable}")
    private int ALIYUN_SMS_ISENABLE;

    @ApiOperation(value = "获取图片验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "imagewidth", value = "图片宽度", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "imageheight", value = "图片高度", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "codelength", value = "验证码位数", dataType = "int", required = false, paramType = "query"),
    })
    @RequestMapping(value = "/getpicvericode", method = RequestMethod.POST)
    BaseResponse getPicVericode(@RequestParam(value = "imagewidth", required = false) Integer imagewidth
            , @RequestParam(value = "imageheight", required = false) Integer imageheight
            , @RequestParam(value = "codelength", required = false) Integer codelength) throws Exception {
        //默认图片宽度
        if (imagewidth == null)
            imagewidth = 115;
        //默认图片高度
        if (imageheight == null)
            imageheight = 48;
        //默认验证码位数
        if (codelength == null)
            codelength = 4;

        //输出图片流
        ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
        //生成图片
        String veriCode = PicVericodeUtils.outputVerifyImage(imagewidth, imageheight, imageStream, codelength);
        // 转码成图片字符串
        String imgString = Base64Util.encode(imageStream.toByteArray());
        //生成token
        String token = UUIDUtil.getUUID();
        //保存验证码数据到redis
        picVericodeService.savePicVericode(token, veriCode);
        //返回结果
        Map<String, Object> result = new HashMap();
        result.put("image", imgString);
        result.put("token", token);
        return new BaseResponse(result);
    }

    @ApiOperation("获取短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号码", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "picvericode", value = "图片验证码", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "pictoken", value = "图片token", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型, 1注册 2短信登录 3找回密码 4重置密码 5 改绑手机", dataType = "int", required = false, defaultValue = "1", paramType = "query")
    })
    @PostMapping("sendvericode")
    BaseResponse sendVericode(@RequestParam("phone") String phone
            , @RequestParam(value = "picvericode") String picvericode
            , @RequestParam(value = "pictoken") String pictoken
            , @RequestParam(value = "type", defaultValue = "1", required = false) int type) throws Exception {

        if (StringHelper.isTrimEmpty(phone)) {
            return new BaseResponse("120", "手机号码不能为空");
        }

        if (type < 0 || type > 5) {
            return new BaseResponse(ReturnCodeConst.ERROR, "请不要进行非法操作");
        }

        phone = phone.trim();
        if (phone.length() != 11 && StringHelper.isInteger(phone) == false) {
            return new BaseResponse("120", "请输入正确的手机号码");
        }

        if (type == 1) {
            if (StringUtils.isEmpty(picvericode)) {
                return new BaseResponse("121", "图片验证码不能为空");
            }

            if (StringUtils.isEmpty(pictoken)) {
                return new BaseResponse("121", "图片验证码错误或已失效");
            }
            if (!picVericodeService.verify(pictoken, picvericode)) {
                return new BaseResponse("121", "图片验证码错误或已失效");
            }
        }

        if (type != 1 && type != 2 && type != 5) {
            String globalToken = global.getFirstToken();
            Map<String, String> header = new HashMap<>();
            header.put("token", globalToken);
            Map<String, Object> query = new HashMap<>();
            query.put("equal_userName", phone);
            query.put("show_total", true);
            int userCount = user_userService.get(header, query).getTotal();
            if (userCount == 0) {
                return new BaseResponse("120", "该手机号码尚未注册，请重新输入！");
            }
        }

        //判断是否达到每日下发次数限制
        int todayMaxCount = 5;

        if (ALIYUN_SMS_ISENABLE == 1) {
            SMSService.sendSms(phone, "1111");
        }

        //smsService.newAsynSMS(smsContent, phone);
        return new BaseResponse("发送成功");
    }


    @ApiOperation(value = "用户注册", notes = "用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号码，11位数字手机号码", dataType = "int", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码，6-12位密码", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱，形如example@163.com, 最大允许50个字符", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "vericode", value = "短信验证码，6位数字验证码", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "source", value = "注册来源 1：iot平台", dataType = "int", paramType = "query"
            )
    })
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    BaseResponse register(@RequestParam("phone") String phone
            , @RequestParam("password") String password
            , @RequestParam("email") String email
            , @RequestParam("vericode") String vericode
            , @RequestParam(value = "source", defaultValue = "1") Integer source
    ) throws Exception {
        if (StringHelper.isTrimEmpty(phone)) {
            return new BaseResponse("120", "手机号码不能为空");
        }

        phone = phone.trim();
        if (phone.length() != 11 && StringHelper.isInteger(phone) == false) {
            return new BaseResponse("120", "请输入正确的手机号码");
        }

        if (StringHelper.isTrimEmpty(email)) {
            return new BaseResponse("121", "邮箱不能为空");
        }

        if (email.length() > 50) {
            return new BaseResponse("121", "邮箱最多允许输入50个字符");
        }

        if (!StringHelper.isEmail(email)) {
            return new BaseResponse("121", "请输入正确的邮箱");
        }

        if (StringHelper.isTrimEmpty(password)) {
            return new BaseResponse("122", "密码不能为空");
        }

        if (password.length() < 6 || password.length() > 12) {
            return new BaseResponse("122", "密码长度为6-12位");
        }

        if (StringHelper.isTrimEmpty(vericode)) {
            return new BaseResponse("124", "短信验证码不能为空");
        }


        //注册用户
        String globalToken = global.getFirstToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", globalToken);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        User_RegistInfoPostModel user_registInfoPostModel = new User_RegistInfoPostModel();
        user_registInfoPostModel.setPhone(Long.parseLong(phone));
        user_registInfoPostModel.setPassword(password);
        user_registInfoPostModel.setEmail(email);
        User_RegistInfoGetModel user_registInfoGetModel = user_user_registInfoService.post(header, query, user_registInfoPostModel);

        User_RegistInfoModel user_registInfoModel = user_registInfoGetModel.getModel();
        Map<String, Object> result = new HashMap<>();
        result.put("uat", user_registInfoModel.getToken());
        result.put("rt", user_registInfoModel.getRsToken());
        return new BaseResponse(result);
    }

    @ApiOperation(value = "完善信息", notes = "完善信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "realname", value = "姓名， 最多允许10个字符", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "idcard", value = "身份证信息，最多允许18个字符", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "公司编号", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/register2", method = RequestMethod.POST)
    BaseResponse register2(@RequestParam("uat") String uat
            , @RequestParam("realname") String realname
//            , @RequestParam("idcard") String idcard
            , @RequestParam(value = "companyId", defaultValue = "0") String companyId
    ) throws Exception {
        if (StringHelper.isTrimEmpty(realname)) {
            return new BaseResponse("121", "姓名不能为空");
        }

        realname = realname.trim();
        if (realname.length() > 10) {
            return new BaseResponse("121", "姓名最多允许输入10个字符");
        }

        //获取用户信息
        String token = getToken();
        UserCardModel userCardModel = getUserCard(token);
        Integer loginUserId = userCardModel.getUserId();

        //完善用户信息
        Map<String, String> header = new HashMap<>();
        header.put("token", global.getFirstToken());
        Map<String, Object> query = new HashMap<>();
        query.put("show", "one");
        User_MoreCompleteRegistInfoPutModel user_moreCompleteRegistInfoPutModel = new User_MoreCompleteRegistInfoPutModel();
        user_moreCompleteRegistInfoPutModel.setCompanyId(Integer.parseInt(companyId));
        user_moreCompleteRegistInfoPutModel.setRealName(realname);
        User_MoreCompleteRegistInfoGetModel user_moreCompleteRegistInfoGetModel = user_user_moreCompleteRegistInfoService.putByUserId(header, loginUserId, query, user_moreCompleteRegistInfoPutModel);

        User_MoreCompleteRegistInfoModel user_moreCompleteRegistInfoModel = user_moreCompleteRegistInfoGetModel.getModel();
        Map<String, Object> result = new HashMap<>();
        result.put("uat", user_moreCompleteRegistInfoModel.getToken());
        result.put("rt", user_moreCompleteRegistInfoModel.getToken());
        return new BaseResponse(result);
    }

    @ApiOperation(value = "用户名/密码登录", notes = "用户名/密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名(手机号码)", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "source", value = "来源 1：iot管理平台", dataType = "int", required = false, paramType = "query"),
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    BaseResponse login(@RequestParam("username") String userName,
                       @RequestParam("password") String password,
                       @RequestParam(value = "source", defaultValue = "1") Integer source) throws Exception {

        if (StringHelper.isTrimEmpty(userName)) {
            return new BaseResponse("120", "用户名不能为空");
        }

        if (StringHelper.isTrimEmpty(password)) {
            return new BaseResponse("121", "密码不能为空");
        }
        Map<String, String> header = new HashMap<>();
        header.put("user-name", userName);
        header.put("password", password);
        Map<String, Object> query = new HashMap<>();
        TokenModel tokenModel = login_tokenService.get(header, query);

       Map<String, Object> result = new HashMap<>();
        result.put("uat", tokenModel.getToken());
        result.put("rt", tokenModel.getRsToken());
        return new BaseResponse(result);
    }

    @ApiOperation(value = "根据RSToken自动登录", notes = "根据RSToken自动登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rstoken", value = "用户RSToken", dataType = "String", required = true, paramType = "query"),
    })
    @RequestMapping(value = "/autologin", method = RequestMethod.POST)
    BaseResponse autologin(@RequestParam("rstoken") String rstoken) throws Exception {

        if (StringHelper.isTrimEmpty(rstoken)) {
            return new BaseResponse("120", "rstoken不能为空");
        }

        //使用rstoken所对应用户名密码进行登录，并刷新该rstoken
        Map<Object, Object> rsTokenObj = redisUtil.hmGetAll(rstoken);
        if (rsTokenObj == null || rsTokenObj.size() == 0) {
            return new BaseResponse(ReturnCodeConst.ERROR, "rstoken无效或已过期");
        }
        String userName = HzhrTypeUtil.object2string(rsTokenObj.get("user-name"));
        String password = HzhrTypeUtil.object2string(rsTokenObj.get("password"));
        Map<String, String> header = new HashMap<>();
        header.put("user-name", userName);
        header.put("password", password);
        Map<String, Object> query = new HashMap<>();
        TokenModel tokenModel = login_tokenService.get(header, query);

        String newRsToken = "cqgas-" + HzhrStringUtils.getGUID();
        redisUtil.set("rsToken:" + userName, newRsToken);
        redisUtil.hmSet(newRsToken, "user-name", userName);
        redisUtil.hmSet(newRsToken, "password", password);
        redisUtil.remove(rstoken);

        HashMap<String, Object> result = new HashMap<>();
        result.put("uat", tokenModel.getToken());
        result.put("rt", newRsToken);
        return new BaseResponse("0", "获取用户信息成功", result);
    }

    @ApiOperation(value = "获取用户权限", notes = "获取用户权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "muat", value = "muat", dataType = "String", required = false, paramType = "query"),
    })
    @RequestMapping(value = "/getActions", method = RequestMethod.POST)
    BaseResponse getActions(@RequestParam("uat") String uat, @RequestParam(value = "appcode", required = false) String appcode,
                            @RequestParam(value = "muat", required = false) String muat) throws Exception {
        UserCardModel userCard = getUserCard(uat);
        if (userCard == null) return new BaseResponse(ReturnCodeConst.NO_LOGIN, "请登录后重试");
        Integer loginUserId = userCard.getUserId();
        String loginUserUserType = userCard.getType();
        String freeTypeCode = userOptions.getCode("USER_TYPE", "FREE");
        if (freeTypeCode.equals(loginUserUserType)){
            Map<String, Object> data = new HashMap<>();
            data.put("type", "None");
            return new BaseResponse("0", "获取权限成功", data);
        }

        Map<String, String> header = new HashMap<>();
        header.put("token", global.getFirstToken());
        Map<String, Object> query = new HashMap<>();
        query.put("show", "list");
        query.put("show_info", true);
        query.put("equal_appCode", 1);
        query.put("equal_userId", loginUserId);
        List<ActionModel> actionModels = user_actionService.get(header, query).getModelList();

        ArrayList<Action> actions = new ArrayList<>();
        for (ActionModel actionModel :
                actionModels) {
            Action action = new Action();
            action.setId(actionModel.getId());
            action.setName(actionModel.getName());
            action.setCode(actionModel.getCode());
            action.setUrl(actionModel.getUrl());
            action.setAssembly("");
            action.setType(HzhrTypeUtil.string2integer(actionModel.getType()));
            action.setParentId(actionModel.getParentId());
            action.setLevel(actionModel.getLevel());
            action.setSort(actionModel.getSort());
            action.setIsvalid(1);
            actions.add(action);
        }

        UserType userType = null;
        if (freeTypeCode.equals(loginUserUserType)){
            userType = UserType.None;
        } else {
            userType = UserType.GasCompanyManager;
        }

        RoleExtent roleExt = new RoleExtent();
        roleExt.setType(userType);
        roleExt.setActions(actions);
        return new BaseResponse("0", "获取权限成功", roleExt);
    }

    @ApiOperation(value = "获取用户详情信息", notes = "获取用户详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "muat", value = "muat", dataType = "String", required = false, paramType = "query"),
    })
    @RequestMapping(value = "/getuserinfo", method = RequestMethod.POST)
    BaseResponse getuserinfo(@RequestParam("uat") String uat, @RequestParam(value = "appcode", required = false) String appcode,
                             @RequestParam(value = "muat", required = false) String muat) throws Exception {
        if (StringHelper.isTrimEmpty(uat) || "undefined".equals(uat)) {
            return new BaseResponse("0", "获取用户信息成功", null);
        }

        String token = getToken();
        UserCardModel userCardModel = getUserCard(token);
        Integer loginUserId = userCardModel.getUserId();

        Map<String, String> header = new HashMap<>();
        header.put("token", global.getFirstToken());
        Map<String, Object> query = new HashMap<>();
        query.put("_show", "one");
        query.put("_show_info", true);
        query.put("_show_dept", true);
        query.put("_show_company", true);
        query.put("_equal_id", loginUserId);
        UserModel userModel = user_userService.get(header, query).getModel();

        User user = new User();
        user.setId(userModel.getId());
        user.setUsername(userModel.getUserName());
        user.setRealname(userModel.getRealName());
        user.setAddr(userModel.getAddr());
        user.setCompanyId(userModel.getCompanyId());
        user.setDeptId(userModel.getDeptId());
        user.setRemarks(userModel.getRemarks());
        user.setCompanyname(userModel.getCompanyName());
        user.setDeptname(userModel.getDeptName());
        user.setIsvalid(1);
        user.setIsManager(0);
        user.setCompanyType(HzhrTypeUtil.string2integer(userModel.getCompanyType()));
        return new BaseResponse("0", "获取用户信息成功", user);
    }
}
